// .erb/scripts/package-with-proxy.js
const { spawn } = require('child_process');

function runCommand(command, args, env) {
  return new Promise((resolve, reject) => {
    const child = spawn(command, args, {
      stdio: 'inherit',
      shell: true,
      env,
    });

    child.on('exit', (code) => {
      if (code === 0) resolve();
      else
        reject(
          new Error(
            `Command "${command} ${args.join(' ')}" exited with code ${code}`
          )
        );
    });
  });
}

async function main() {
  // 复制当前环境变量，注入代理
  const env = { ...process.env };
  env.HTTP_PROXY = 'http://127.0.0.1:12333';
  env.HTTPS_PROXY = 'http://127.0.0.1:12333';
  env.ELECTRON_GET_USE_PROXY = '1';

  console.log('✅ 设置代理环境变量:', env.HTTPS_PROXY);

  try {
    // 按顺序执行你之前的命令：
    await runCommand('ts-node', ['.erb/scripts/clean.js', 'dist'], env);
    await runCommand('npm', ['run', 'build'], env);
    await runCommand('electron-builder', ['build', '--publish', 'never'], env);
    await runCommand('npm', ['run', 'build:dll'], env);
    console.log('🎉 打包成功！');
  } catch (err) {
    console.error('❌ 打包失败:', err);
    process.exit(1);
  }
}

main();
